package cn.zsc.netdisk.handler;

import cn.zsc.netdisk.exception.IllegalPasswordException;
import cn.zsc.netdisk.exception.UserAccountNotFoundException;
import cn.zsc.netdisk.pojo.User;
import cn.zsc.netdisk.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 * @author ccying
 * @date 2021/2/4
 */
@Component
@Slf4j
public class AuthenticationProviderHandler implements AuthenticationProvider {
    private final UserService userService;
    private final PasswordEncoderHandler passwordEncoder;

    public AuthenticationProviderHandler(UserService userService, PasswordEncoderHandler passwordEncoder) {
        this.userService = userService;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        System.out.println("*************************************************");
        String uid = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();
        log.info(String.format("用户【%s，%s】请求登录", uid, password));

        User user = userService.findUserByUid(uid);
        if (user == null) {
            throw new UserAccountNotFoundException("用户账号不存在");
        } else {
            if (passwordEncoder.matches(password, user.getPassword())) {
                return new UsernamePasswordAuthenticationToken(user.getUid(), user.getPassword(), null);
            }else {
                throw new IllegalPasswordException("用户密码错误");
            }
        }
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
